package cn.wsalix.weixin.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import cn.anlaser.entity.SimpleEntity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "WX_MENU")
@Inheritance(strategy = InheritanceType.JOINED)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@EntityListeners({ AuditingEntityListener.class })
@Data
@EqualsAndHashCode(callSuper = false, exclude = { "parent", "sub" })
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({ "id", "createdBy", "createdDate", "lastModifiedBy",
		"lastModifiedDate", "serNo", "delFlag","parent","new" })
@JsonInclude(Include.NON_NULL)
public class WxMenu extends SimpleEntity {

	public WxMenu(String name) {
		super.setName(name);
	}

	private static final long serialVersionUID = -4578429578864603158L;
	@ManyToOne(cascade = CascadeType.MERGE, optional = true, fetch = FetchType.LAZY)
	@JoinColumn(foreignKey = @ForeignKey(name = "FK_WXMENU_PARENT"), name = "PARENT_ID")
	private WxMenu parent;

	private String type;

	private String mkey;

	private String url;
	@JsonProperty("sub_button")
	@OneToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY, mappedBy = "parent")
	private List<WxMenu> sub;

	public WxMenu addMenus(WxMenu... wxMenus) {
		if (getSub() == null) {
			setSub(new ArrayList<WxMenu>());
		}
		for (WxMenu wxMenu : wxMenus) {
			getSub().add(wxMenu);
		}
		return this;
	}

	public WxMenu(WxMenu... wxMenus) {
		if (getSub() == null) {
			setSub(new ArrayList<WxMenu>());
		}
		for (WxMenu wxMenu : wxMenus) {
			getSub().add(wxMenu);
		}
	}

	public WxMenu(String type, String name, String key) {
		this.type = type;
		this.setName(name);
		this.mkey = key;
	}

}
